<?php
/**
 * Created by PhpStorm.
 * User: DaveTang
 * Date: 2020/3/3
 * Time: 15:56
 * 用户信息缓存组件
 */

namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\Cache\Cache;

class ViewCacheComponent extends Component
{

    public $_cache_config = 'views';
    private $_update_db_time = 6000;//下次更新时间（秒）
    public function initialize(array $config)
    {
        parent::initialize($config);
    }

    /**
     * 获取浏览量缓存
     * @param  $content_type  表名
     * @param  $content_id   表id
     */
    public function getVal($content_type, $content_id)
    {
        $key = 'views_'.$content_type . '_' . $content_id;
        $data = Cache::read($key, $this->_cache_config);
        return empty($data) ? $this->createCache($content_type, $content_id) : $data;
    }

    /**
     * 创建浏览量缓存
     * @param  $content_type  表名
     * @param  $content_id   表id
     */
    public function createCache($content_type, $content_id)
    {
        $key = 'views_'.$content_type . '_' . $content_id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Views');
        $data = $controller->Views->find()
            ->where(['content_type' => $content_type, 'content_id'=>$content_id])
            ->first();
        $cache = empty($data) ? null : ['id'=>$data['id'], 'v'=>$data['view'], 'p'=>$data['pre_view'], 't'=>time() + $this->_update_db_time];
        Cache::write($key, $cache, $this->_cache_config);
        return $cache;
    }

    /**
     * 更新浏览量缓存
     * @param  $content_type  表名
     * @param  $content_id   表id
     * @param  $view   数据
     */
    public function updateCache($content_type, $content_id, $view)
    {
        $key = 'views_'.$content_type . '_' . $content_id;
        $controller = $this->_registry->getController();
        $controller->loadModel('Views');
        $data = $this->getVal($content_type, $content_id);
        $view['v'] = empty($view['v']) ? 0 : $view['v'];
        $view['p'] = empty($view['p']) ? 0 : $view['p'];
        if(empty($data)){
            $views = $controller->Views->newEntity();
            $views->content_type = $content_type;
            $views->content_id = $content_id;
            $views->view = $view['v'];
            $views->pre_view = $view['p'];
            $controller->Views->save($views);
            $this->createCache($content_type, $content_id);
        }else{
            $data['v'] = $data['v'] + $view['v'];
            $data['p'] = $view['p'];
            if($data['t'] < time()){
                $controller->Views->query()
                    ->update()
                    ->set(['view'=>$data['v'], 'pre_view'=>$data['p']])
                    ->where(['id' => $data['id']])
                    ->execute();
                $data['t'] = time() + $this->_update_db_time;
            }
            Cache::write($key, $data, $this->_cache_config);
        }
    }

}